package com.joycessh.shiro;

import com.joycessh.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author Joycessh
 * @Description
 * @Date 8/18/19 3:30 PM
 */
@Slf4j
@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        AccountProfile accountProfile = userService.login(token.getUsername(), String.valueOf(token.getPassword()));

        SecurityUtils.getSubject().getSession().setAttribute("profile", accountProfile);

        log.info("------------------->进入shiro登录认证流程");
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(accountProfile, token.getCredentials(), getName());

        return simpleAuthenticationInfo;
    }
}
